<template>
  <el-drawer
    :title="titleTip"
    size="700px"
    :close-on-click-modal="false"
    v-if="dialogVisible"
    direction="rtl"
    @close="handleCloseDialog"
    :visible="dialogVisible"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      class="infoForm"
      style="width: 700px"
      label-width="120px"
      :disabled="disable"
    >
      <el-form-item label="类型" prop="question_type">
        <el-radio-group
          @input="handleChangeType"
          v-model="ruleForm.question_type"
        >
          <el-radio label="0">单选题</el-radio>
          <el-radio label="2">多选题</el-radio>
          <el-radio label="1">问答题</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题目描述" prop="question" style="width: 650px">
        <el-input
          style="float: left; display: inline-block; width: 420px"
          type="textarea"
          autosize
          :rows="1"
          v-model="ruleForm.question"
        ></el-input>
        <div
          v-if="ruleForm.question_file"
          style="width: 200px; margin-top: 40px"
        >
          <img
            style="width: 100%"
            @click="handleLookImg('question', ruleForm.question_file)"
            :src="ruleForm.question_file"
          />
        </div>
        <UploadLink
          :showFileList="false"
          :files.sync="ruleForm.images"
          v-else
          style="float: left; margin-left: 10px"
          @update:files="changeQuestionFile"
          :isCustomTrigger="true"
        >
          <template #trigger_btn>
            <el-button type="primary">添加附件</el-button>
          </template>
        </UploadLink>
      </el-form-item>
      <el-form-item
        label="选项"
        prop="options"
        style="width: 635px"
        v-if="ruleForm.question_type === '0' || ruleForm.question_type === '2'"
      >
        <div class="option-wrap">
          <div class="option-item title">
            <div class="item-input">选项内容</div>
            <div class="item-img">图片</div>
            <div class="item-check">正确答案</div>
          </div>
          <div
            class="option-item"
            v-for="(item, index) in ruleForm.options"
            :key="index"
            style="padding-bottom: 5px"
          >
            <!-- <el-tag>{{ index }}</el-tag> -->
            <el-input
              class="item-input"
              type="textarea"
              autosize
              :rows="1"
              v-model="item.option_content"
            ></el-input>
            <div class="item-img">
              <img
                v-if="item.option_file"
                @click="handleLookImg('option', item.option_file, index)"
                :src="item.option_file"
              />
              <template v-else>
                <UploadLink
                  :files.sync="item.files"
                  @update:files="(files) => changeOptionFile(files, index)"
                  :showFileList="false"
                  :isCustomTrigger="true"
                >
                  <!-- <i slot="trigger" style="font-size: 24px;color: gray;"
                                        class="el-icon-picture-outline"></i> -->
                  <template v-slot:trigger_btn>
                    <i
                      style="font-size: 24px; color: gray"
                      class="el-icon-picture-outline"
                    ></i>
                  </template>
                </UploadLink>
              </template>
            </div>
            <div class="item-check">
              <el-checkbox
                style="padding-left: 10px"
                @change="handleChangeAnswer(item, index)"
                v-model="item.is_true"
                :true-label="1"
                :false-label="0"
              >
              </el-checkbox>
            </div>
            <div class="item-icons">
              <div style="padding-left: 10px; display: flex">
                <el-button
                  type="info"
                  @click="handleOperationAdd"
                  style="margin-left: 3px; height: 26px; padding: 0 6px"
                  size="mini"
                  plain
                  icon="el-icon-plus"
                  circle
                ></el-button>
                <el-button
                  type="info"
                  @click="handleOperationDel(index)"
                  style="margin-left: 3px; height: 26px; padding: 0 6px"
                  size="mini"
                  plain
                  icon="el-icon-minus"
                  circle
                ></el-button>
              </div>

              <!-- <div v-if="!disable">
                                <i @click="handleOperationAdd" class="el-icon-circle-plus-outline"
                                    style="font-size: 24px"></i>
                            </div>
                            <div v-if="!disable" style="width:24px;margin-left: 10px;">
                                <i @click="handleOperationDel(index)" class="el-icon-remove-outline"
                                    style="font-size: 24px"></i>
                            </div> -->
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label="参考答案"
        prop="refer_to_answer"
        v-if="ruleForm.question_type === '1'"
      >
        <el-input
          type="textarea"
          style="width: 420px"
          autosize
          :rows="2"
          v-model="ruleForm.refer_to_answer"
        ></el-input>
      </el-form-item>
      <el-form-item label="分数" prop="score">
        <!-- <el-input type="text" v-model="ruleForm.score"></el-input> -->
        <el-autocomplete
          class="inline-input"
          v-model="ruleForm.score"
          :fetch-suggestions="querySearchScore"
          placeholder="请输入分数"
          @select="handleSelectScore"
        ></el-autocomplete>
      </el-form-item>
    </el-form>
    <div class="dialog-footer" style="text-align: center; padding-top: 20px">
      <el-button @click="handleCloseDialog">取消</el-button>
      <el-button type="primary" @click="handlePreview">预览</el-button>

      <el-button type="primary" @click="handleClickSubmit">确定</el-button>
    </div>
    <el-dialog :visible.sync="imgDialogVisible" append-to-body>
      <div style="text-align: right; margin-bottom: 10px">
        <UploadLink
          @update:files="(files) => reChangeOptionFile(files)"
          :showFileList="false"
          :isCustomTrigger="true"
        >
          <template #trigger_btn>
            <el-button type="primary">重新上传</el-button>
          </template>
        </UploadLink>
      </div>
      <img width="100%" :src="dialogImageUrl" alt="" />
      <div class="dialog-footer" style="text-align: center; padding-top: 20px">
        <el-button @click="imgDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="reUploadOk">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="previewDialogVisible" append-to-body>
      <Question :data="ruleForm" mode="detail"></Question>
    </el-dialog>
  </el-drawer>
</template>

<script>
import UploadLink from "@/components/uploadFile/uploadLink.vue";
import {
  ExamQuestionCreate,
  ExamQuestionDetail,
  ExamQuestionUpdate,
} from "@/api/qms.js";
import Question from "./question/index.vue";
export default {
  name: "trainMaterial",
  components: { UploadLink, Question },
  props: ["dialogVisible", "mode", "id"],
  data() {
    return {
      imgDialogVisible: false,
      dialogImageUrl: "",
      lookType: "",
      lookIndex: "",
      ruleForm: {
        question: "", // 题目
        question_type: "0", // 题型：0-单选，1-问答题 2-多选
        refer_to_answer: "", // 参考答案
        score: "", // 分数
        options: [],
        images: [],
      },
      rules: {
        question: [
          { required: true, message: "请输入题目描述", trigger: "blur" },
        ],
        score: [{ required: true, message: "请输入分数", trigger: "blur" }],
      },
      OPTIONS: ["A", "B", "C", "D", "E", "F", "G"],
      singleOption: {
        option_content: "", // 选项内容
        option_file: "", // 选项附件
        is_true: 0, // 是否是正确答案：0-否，1-是
      },
      scoreData: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      previewDialogVisible: false,
    };
  },
  computed: {
    name() {
      return this.data;
    },
    isSingleCheck() {
      return this.ruleForm.question_type === "0";
    },
    isDiscuss() {
      return this.ruleForm.question_type === "1";
    },
    disable() {
      return this.mode === "detail";
    },
    titleTip() {
      const { mode } = this;
      if (mode === "add") {
        return "新建考题";
      } else if (mode === "edit") {
        return "编辑考题";
      } else {
        return "考题详情";
      }
    },
  },
  mounted() {
    // console.log(this.mode, 'ppppppppppppppp');
    if (this.mode === "add") {
      this.ruleForm.options = this.getInitOptions();
    } else if (this.mode === "edit" || this.mode === "detail") {
      this.getDetail();
    }
  },
  methods: {
    handlePreview() {
      this.previewDialogVisible = true;
    },
    handleLookImg(type, val, index) {
      this.lookType = type;
      this.dialogImageUrl = val;
      this.imgDialogVisible = true;
      if (type === "option") {
        this.lookIndex = index;
      }
    },
    changeQuestionFile(files) {
      this.ruleForm.question_file = files[0].url;
    },
    changeOptionFile(files, index) {
      // console.log(files, index, 'files,index');
      this.ruleForm.options[index].option_file = files[0].url;
    },
    reChangeOptionFile(files) {
      // console.log(files, 'files');
      this.dialogImageUrl = files[0].url;
    },
    reUploadOk() {
      if (this.lookType === "option") {
        this.ruleForm.options[this.lookIndex].option_file = this.dialogImageUrl;
      } else {
        this.ruleForm.question_file = this.dialogImageUrl;
      }
      this.imgDialogVisible = false;
    },
    querySearchScore(queryString, cb) {
      const scoreData = this.scoreData.map((item) => {
        return {
          value: item + "",
        };
      });
      let results = queryString
        ? scoreData.filter((item) => item.value.indexOf(queryString + "") === 0)
        : scoreData;
      cb(results);
    },

    handleSelectScore(item) {
      // console.log(item);
    },

    handleChangeType() {
      if (this.isDiscuss) {
        this.ruleForm.options = this.getInitOptions();
      }
    },
    getInitOptions() {
      const { singleOption } = this;
      return [
        {
          ...singleOption,
        },
        { ...singleOption },
      ];
    },
    handleChangeAnswer(item, index) {
      if (this.isSingleCheck) {
        for (let i = 0; i < this.ruleForm.options.length; i++) {
          if (i !== index) {
            this.ruleForm.options[i].is_true = 0;
          }
        }
      }

      const OPTIONS = ["A", "B", "C", "D", "E", "F", "G"];
    },
    handleClickSubmit() {
      // this.$refs["ruleForm"].validate((valid) => {
      //     if (!valid) return;
      const _ruleForm = {
        ...this.ruleForm,
        score: this.ruleForm.score * 1,
      };
      if (this.mode === "add") {
        ExamQuestionCreate(_ruleForm).then((res) => {
          if (res.code === 10000) {
            this.$message({
              message: "新增成功",
              type: "success",
            });
            this.$emit("close", true);
          }
        });
      } else {
        ExamQuestionUpdate(_ruleForm).then((res) => {
          if (res.code === 10000) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.$emit("close", true);
          }
        });
      }
    },
    handleOperationAdd() {
      this.ruleForm.options.push({
        ...this.singleOption,
      });
    },
    handleOperationDel(index) {
      this.ruleForm.options.splice(index, 1);
    },
    handleCloseDialog() {
      this.$emit("close");
    },
    getDetail() {
      ExamQuestionDetail({
        id: this.id * 1,
      }).then((res) => {
        const data = res.data;
        data.options = data.option_content;
        data.score = data.score + "";
        this.ruleForm = data;
        // 选择题
        // if (data.question_type == '0') {
        //     const index = this.OPTIONS.findIndex(item => item === data.refer_to_answer);
        //     this.ruleForm.options[index].is_true = true;
        // }
      });
    },
    handleExceed(_, fileList) {
      this.$message.warning(`只能选择 ${fileList.length} 个文件上传`);
    },
    // getDetail() {
    //     trainingMaterialDetail({
    //         id: this.id
    //     }).then(res => {
    //         // console.log(res, 'eeeeee');
    //     });
    // },
    handleClickSubmit1() {
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        let _ruleForm = {
          ...this.ruleForm,
          storage_url: this.ruleForm.storage_url[0].url,
        };
        if (this.mode === "add") {
          trainingMaterialCreate({
            material_list: [_ruleForm],
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "新建成功",
                type: "success",
              });
              this.$emit("close", true);
            }
          });
        } else {
          trainingMaterialUpdate(_ruleForm).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.$emit("close", true);
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
}

.infoForm {
  .el-input {
    width: 200px;
  }

  .el-select,
  .el-textarea,
  .el-cascader {
    width: 200px;
  }

  .check-radio {
    margin-top: 10px;

    /deep/.el-radio {
      width: 100%;
      padding-bottom: 10px;

      .el-radio__label {
        padding-left: 5px;
      }
    }
  }

  /deep/.inline-input .el-input--mini .el-input__inner {
    height: 30px !important;
    line-height: 30px !important;
  }

  .option-wrap {
    .option-item {
      display: flex;

      &.title {
        background: #e5e4e4;
        margin-bottom: 8px;

        .item-input {
          padding-left: 3px;
        }
      }

      .item-input {
        flex: 0 0 290px;
        padding-right: 10px;
      }

      .item-img {
        flex: 0 0 50px;
        height: 28px;

        img {
          width: 28px;
          height: 100%;
        }
      }

      .item-check {
        flex: 0 0 60px;
        padding-right: 10px;
      }

      .item-icons {
        flex: 0 0 100px;
      }
    }
  }
}
</style>